package org.luxor.common.netty.jdk.bio.server;

import org.luxor.commons.core.utils.DateUtils;
import org.luxor.commons.core.utils.IoUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

public class TimeServerHandler implements Runnable {
    private Socket socket;

    public TimeServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            out = new PrintWriter(this.socket.getOutputStream());
            while (true) {
                // 从客户端读取指令
                String body = in.readLine();
                if (body == null) {
                    break;
                }
                System.out.println("The time server receive order : " + body);

                // 向客户端写入响应
                if ("QUERY TIME ORDER".equalsIgnoreCase(body)) {
                    out.println(DateUtils.format(new Date(), DateUtils.DATE_FORMAT_19_FORWARD_SLASH));
                } else {
                    out.println("BAD ORDER");
                }
                out.flush();
            }
        } catch (Exception e) {
            IoUtils.closeQuietly(in);
            IoUtils.closeQuietly(out);
        }
    }
}
